﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace XYS.Service.Core.Util.Converters
{
    /// <summary>
    /// 处理 ISO 8601 格式日期
    /// </summary>
    public class CustomDateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var dateString = reader.GetString();
            if (DateTime.TryParse(dateString, out var dateTime))
            {
                return dateTime;
            }

            // 如果解析失败，可以抛出异常或返回默认值
            throw new JsonException("Invalid date format");
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-ddTHH:mm:ss"));
        }
    }
}
